package com.wifi.IBackService;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Arrays;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.wifi.utils.Utils;
import com.wifi.utils.WifiUtils;

/**
 * Created by Administrator on 2016/10/7.
 */
public class ThreadServiceV0 extends Service {

        private static final String TAG = "BackService";
        private static final long HEART_BEAT_RATE = 10 * 1000;//10秒

        public static  String HOST = "192.168.77.1";// "192.168.1.21";//
        public static  int PORT = 8888;

        public static final String MESSAGE_ACTION="org.feng.message_ACTION";
        public static final String HEART_BEAT_ACTION="org.feng.heart_beat_ACTION";
        public static final String WIFI_REBOOT="org.feng.wifi_reboot";

        private ReadThread mReadThread;

        private LocalBroadcastManager mLocalBroadcastManager;

        private WeakReference<Socket> mSocket;

        // For heart Beat
        private Handler mHandler = new Handler();
        WifiUtils wifiUtils;
        String connectedSSID;
        private Runnable heartBeatRunnable = new Runnable() {
            @Override
            public void run() {
                if (System.currentTimeMillis() - sendTime >= HEART_BEAT_RATE) {
                    boolean isSuccess = sendMsg("$heartbeat;");//就发送一个\r\n过去 如果发送失败，就重新初始化一个socket
                    if (!isSuccess) {//重新连接
                        //获取系统服务
                        //获取状态
                        WifiInfo wifiInfo = wm.getConnectionInfo();
                        connectedSSID = wifiInfo.getSSID();
                        connectedSSID=connectedSSID.replace("\"","");
                        sp= getSharedPreferences("wifiSetting", Activity.MODE_PRIVATE);
                        String ssid = sp.getString("ssid", "sn1111111");//是否为上一次连接的wifi
                        if(connectedSSID.indexOf(ssid)!=-1){//相同 重新连接
                            mHandler.removeCallbacks(heartBeatRunnable);
                            mReadThread.release();
                            releaseLastSocket(mSocket);
                            new InitSocketThread().start();
                        }else {//否则重启wifi
                            Intent intent=new Intent(WIFI_REBOOT);
                            intent.putExtra("wifiReboot", "wifiReboot");
                            mLocalBroadcastManager.sendBroadcast(intent);
                        }


                    }
                }
                mHandler.postDelayed(this, HEART_BEAT_RATE);
            }
        };

        private long sendTime = 0L;

        private IBackService.Stub iBackService = new IBackService.Stub() {

            @Override
            public boolean sendMessage(String message) throws RemoteException {
                return sendMsg(message);
            }

            @Override
            public boolean sendFile(String path) throws RemoteException {
                return SendFile(path);
            }

            @Override
            public void getNetSocket() throws RemoteException {
                mHandler.removeCallbacks(heartBeatRunnable);
                releaseLastSocket(mSocket);
                new InitSocketThread().start();
            }
        };

        @Override
        public IBinder onBind(Intent arg0) {
            return iBackService;
        }

        WifiManager wm;
        SharedPreferences sp;
        @Override
        public void onCreate() {
            super.onCreate();
            wm = (WifiManager) getSystemService(WIFI_SERVICE);

            new InitSocketThread().start();
            mLocalBroadcastManager=LocalBroadcastManager.getInstance(this);
        }

        public boolean SendFile(String path){
            try {
                Socket soc = mSocket.get();
                OutputStream outputData = soc.getOutputStream();
                FileInputStream fileInput = new FileInputStream(path);
                int size = -1;
                byte[] buffer = new byte[1024];
                while((size = fileInput.read(buffer, 0, 1024)) != -1){
                    outputData.write(buffer, 0, size);
                }
//                return fileName + " 发送完成";
//todo                outputData.close();
//                fileInput.close();
                return true;
            } catch (Exception e) {
//                return "发送错误:\n" + e.getMessage();
                return false;
            }
        }


        public boolean sendMsg(String msg) {
            if(msg==""){

            }else {
                if (null == mSocket || null == mSocket.get()) {
                    return false;
                }
                Socket soc = mSocket.get();
                try {
                    if (!soc.isClosed() && !soc.isOutputShutdown()) {
                        //todo 接受数据
                        OutputStream os = soc.getOutputStream();
                        String message = msg + "\r\n";
                        os.write(message.getBytes());
                        os.flush();
                        sendTime = System.currentTimeMillis();//每次发送成数据，就改一下最后成功发送的时间，节省心跳间隔时间
                    } else {
                        return false;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
            return true;
        }

        private void initSocket() {//初始化Socket
            DhcpInfo di = wm.getDhcpInfo();
            long getewayIpL = di.gateway;
            String getwayIpS = Utils.long2ip(getewayIpL);//网关地址
            this.HOST=getwayIpS;
            try {
                Socket so = new Socket(HOST, PORT);
                mSocket = new WeakReference<Socket>(so);
                sendMsg("$first_connect;");
                mReadThread = new ReadThread(so);
                mReadThread.start();
                mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//初始化成功后，就准备发送心跳包
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        private void releaseLastSocket(WeakReference<Socket> mSocket) {
            try {
                if (null != mSocket) {
                    Socket sk = mSocket.get();
                    if(sk!=null){
                        if (!sk.isClosed()) {
                            sk.close();
                        }
                        sk = null;
                        mSocket = null;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        class InitSocketThread extends Thread {
            @Override
            public void run() {
                super.run();
                initSocket();
            }
        }

        // Thread to read content from Socket
        class ReadThread extends Thread {
            private WeakReference<Socket> mWeakSocket;
            private boolean isStart = true;

            public ReadThread(Socket socket) {
                mWeakSocket = new WeakReference<Socket>(socket);
            }

            public void release() {
                isStart = false;
                releaseLastSocket(mWeakSocket);
            }

            @Override
            public void run() {
                super.run();
                Socket socket = mWeakSocket.get();
                if (null != socket) {
                    try {
                        InputStream is = socket.getInputStream();
                        byte[] buffer = new byte[1024 * 4];
                        int length = 0;
                        while (!socket.isClosed() && !socket.isInputShutdown()
                                && isStart && ((length = is.read(buffer)) != -1)) {
                            if (length > 0) {
                                String message = new String(Arrays.copyOf(buffer,
                                        length)).trim();
                                Log.e(TAG, message);
                                //收到服务器过来的消息，就通过Broadcast发送出去
                                if(message.equals("heartbeat")){//处理心跳回复
                                    Intent intent=new Intent(HEART_BEAT_ACTION);
                                    mLocalBroadcastManager.sendBroadcast(intent);
                                }else  if(message.indexOf("wrong_cmd")!=-1){//心跳包响应

                                }else{
                                    //其他消息回复
                                    Intent intent=new Intent(MESSAGE_ACTION);
                                    intent.putExtra("message", message);
                                    mLocalBroadcastManager.sendBroadcast(intent);
                                }
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

}
